package com.ywl.filter;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.ywl.domain.LoginUser;
import com.ywl.utlis.JwtUtil;
import com.ywl.utlis.RedisCache;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @author 24040
 * @name JwtAuthenticationTokenFilter
 * @date 2022-10-16 11:53
 */

@Component
//选择不继承filter接口，而是去实现oncePerRequestFilter，这样可以避免一次请求 调用多次过滤器
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)){
            //放行
            filterChain.doFilter(request,response);
            return;
        }

        //解析token
        String userId = "";
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("token 非法");
        }
        //从redis中获取用户信息
        String redisKey = "login:" + userId;

        String loginUserStr = redisTemplate.opsForValue().get(redisKey);
        if(StrUtil.isBlank(loginUserStr)){
            throw new RuntimeException("用户未登录");
        }

        LoginUser loginUser = JSON.parseObject(loginUserStr, LoginUser.class);
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("用户未登陆");
        }

        // TODO 获取权限信息，封装到 Authentication
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser
                        , null,loginUser.getAuthorities() );

        // 存入securityContextHolder当中
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request,response);
    }
}
